// import 'package:flutter/material.dart';
//
// class ContactsPage extends StatelessWidget {
//   const ContactsPage({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return const Center(
//       child: Text(
//         '暂无联系人！',
//         style: TextStyle(fontSize: 24, color: Colors.orange),
//       ),
//     );
//   }
// }

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:webview_flutter/webview_flutter.dart';

class ContactsPage extends StatefulWidget {
  const ContactsPage({super.key});

  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  final TextEditingController _controller = TextEditingController();
  Map<String, dynamic>? _data;
  bool _isLoading = false;
  late final WebViewController _webViewController;
  bool _webViewLoaded = false;

  Future<void> _search(String bkKey) async {
    const String appid = '379020';
    final String url =
        'https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?appid=$appid&bk_key=$bkKey';

    setState(() {
      _isLoading = true;
      _data = null;
      _webViewLoaded = false;
    });

    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        setState(() {
          _data = json.decode(response.body);
        });
        if (_data!['url'] != null) {
          _webViewController.loadRequest(Uri.parse(_data!['url']));
        }
      } else {
        _showError('Failed to load data. Status code: ${response.statusCode}');
      }
    } catch (e) {
      _showError('An error occurred: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  void initState() {
    super.initState();
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (_) {
            setState(() {
              _webViewLoaded = true;
            });
          },
        ),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: const InputDecoration(
                      // labelText: '请输入搜索关键词',
                      hintText: '请输入搜索关键词',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 5),
                SizedBox(
                  height: 48, // 设置按钮的高度以与输入框对齐
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      //primary: Theme.of(context).primaryColor,
                      backgroundColor: Colors.blue,
                    ),
                    onPressed: () {
                      if (_controller.text.isNotEmpty) {
                        _search(_controller.text);
                      } else {
                        _showError('请输入搜索关键字');
                      }
                    },
                    child: const Text('百度搜索', style: TextStyle(color: Colors.white)),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 5),
            const Align(
              alignment: Alignment.centerLeft,
              child: Text(
                '建议搜索某个关键词或短语，不要直接搜索整句话',
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
            ),
            const SizedBox(height: 10),
            if (_isLoading) const CircularProgressIndicator(),
            if (_data != null)
              Expanded(
                child: Column(
                  children: [
                    if (_data!['url'] != null)
                      Expanded(
                        child: Stack(
                          children: [
                            WebViewWidget(controller: _webViewController),
                            if (!_webViewLoaded)
                              const Center(child: CircularProgressIndicator()),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }
}



